package com.stars.easyms.logging.appender;

import com.plumelog.core.MessageAppenderFactory;
import com.plumelog.core.dto.BaseLogMessage;
import com.plumelog.core.dto.RunLogMessage;
import com.plumelog.log4j2.util.LogMessageUtil;
import com.stars.easyms.base.trace.EasyMsTraceSynchronizationManager;
import com.stars.easyms.logging.properties.EasyMsLoggingPlumeLogHelper;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Property;

import java.util.concurrent.atomic.LongAdder;

/**
 * <p>className: EasyMsPlumeLogAppender</p>
 * <p>description: EasyMs的plumeLog的appender</p>
 *
 * @author guoguifang
 * @version 1.7.2
 * @date 2021/1/21 4:53 下午
 */
public class EasyMsPlumeLogAppender extends AbstractAppender {

    private static final LongAdder ADDER = new LongAdder();

    public EasyMsPlumeLogAppender(String name) {
        super(name, null, null, true, Property.EMPTY_ARRAY);
    }

    @Override
    public void append(LogEvent logEvent) {
        if (EasyMsLoggingPlumeLogHelper.isAppenderEnabled()) {
            final BaseLogMessage logMessage = LogMessageUtil.getLogMessage(EasyMsLoggingPlumeLogHelper.getAppName(), logEvent);
            if (logMessage instanceof RunLogMessage) {
                String traceId = logMessage.getTraceId();
                if (traceId == null) {
                    traceId = EasyMsTraceSynchronizationManager.getTraceId();
                    if (traceId != null) {
                        logMessage.setTraceId(traceId);
                    }
                    // 如果是异步线程则把异步id也加到日志里
                    String asyncId = EasyMsTraceSynchronizationManager.getAsyncId();
                    if (asyncId != null) {
                        RunLogMessage runLogMessage = (RunLogMessage) logMessage;
                        runLogMessage.setContent("[asyncId: " + asyncId + "] " + runLogMessage.getContent());
                    }
                }
                MessageAppenderFactory.pushRundataQueue(LogMessageUtil.getLogMessage(logMessage, logEvent));
                ADDER.increment();
            }
        }
    }

    public static long getCount() {
        return ADDER.longValue();
    }
}
